package com.bdqn.controller;

import com.bdqn.entity.UmsUser;
import com.bdqn.entity.responseDate.cart.OmsCartDto;
import com.bdqn.entity.util.RespBean;
import com.bdqn.service.OmsCartService;
import com.bdqn.service.UmsUserService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/oms/cart")
public class OmsCartController {
    Logger logger = LoggerFactory.getLogger(OmsCartController.class);
    @Autowired
    private OmsCartService omsCartService;
    @Autowired
    private UmsUserService umsUserService;
    @PostMapping("/add")
    public RespBean add(HttpServletRequest request, Long skuId, Integer num) {

        //userId的话  同token进行获取
        String token = request.getHeader("token");
        UmsUser user = umsUserService.getUserByToken(token);
        int add = omsCartService.add(skuId, num, user.getId());
        if (add > 0) {
            return RespBean.ok("添加购物车成功", add);
        } else {
            return RespBean.err("添加购物车失败");
        }
    }

    @GetMapping("/cartCount")
    public RespBean cartCount(HttpServletRequest request) {
        //查询购物车总数   通过用户id和商品
        String token = request.getHeader("token");
        UmsUser userByToken = umsUserService.getUserByToken(token);
        int count = omsCartService.cartCount(userByToken.getId());
        Map<String, Object> map = new HashMap<>();
        map.put("cartCount", count);
        if (count > 0) {
            return RespBean.ok("获取购物商品数量成功", map);
        } else {
            return RespBean.err("获取购物商品数量失败");
        }
    }

    /**
     * 通过key获取到购物车的商品信息
     *
     * @return
     */
    @GetMapping("/cartList")
    public RespBean cartList(HttpServletRequest request) {
        String token = request.getHeader("token");
        UmsUser userByToken = umsUserService.getUserByToken(token);
        List<OmsCartDto> list = omsCartService.cartList(userByToken.getId());
        if(list.size()>0){
            return RespBean.ok("获取购物车列表成功",list);
        }else {
            return RespBean.err("获取购物车列表失败");
        }
    }
    @PostMapping("/remove")
    public RespBean remove(List<Long> skuIds,HttpServletRequest request){
        //通过token获取用户对象
        String token = request.getHeader("token");
        UmsUser userByToken = umsUserService.getUserByToken(token);
        int remove = omsCartService.remove(userByToken.getId(), skuIds);

        return remove>0?RespBean.ok("从redis中删除购物信息成功",remove):RespBean.err("从redis中删除购物信息失败");
    }
}
